package com.example.homework7;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class external extends Fragment {
    private String FILE_NAME = "ExternalStorage.txt";
    public external() {
        super(R.layout.external);
    }
    public void onViewCreated(@NonNull View view, @NonNull Bundle saveInstanceState) {
        super.onViewCreated(view, saveInstanceState);
        Button writeExternalButton = getView().findViewById(R.id.external_button);
        writeExternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File externalPath = getActivity().getExternalFilesDir(null);
                File file = new File(externalPath, FILE_NAME);
                try {
                    FileOutputStream os = getActivity().openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
                    writer.write("I'm dodo.This is data stored externally.");
                    writer.close();
                    Toast.makeText(getActivity(), "外部数据写入成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}